import Shios from "./shios";
export class RequestCache extends Shios {
  constructor(baseUrl) {
    super(baseUrl);
    this.caches = new Map();
    // this.data = JSON.parse(window.sessionStorage.getItem("token"));
  }
  // data;
  async clearCaches() {
    let cacheKeys = await window.caches.keys();
    let deleted = cacheKeys.every(async (v) => await window.caches.delete(v));
    if (!deleted) {
      throw "delete failed!";
    }
  }
  async get(...params) {
    // let url = super.joinUrl(...params);
    // console.log(this.caches);
    // if (this.caches.has(url)) {
    //   // console.log(this.caches);
    //   return this.caches.get(url);
    // }

    let { data } = await super.get(...params);

    // this.caches.set(url, data);
    // console.log(this.caches);
    return data;
  }
  async get2(...params) {
    if (!window.caches || process.env.NODE_ENV == "development") {
      let response = await super.get(...params);
      return response.data;
    }
    let [action, id] = params;

    let url = super.joinUrl(action, id);
    let req = new Request(url, {
      headers: {
        userId: this.userId,
        token: this.token,
      },
    });
    let cacheName = /(?<=\/api\/)[A-z]+/.exec(action)[0];

    let cached = window.sessionStorage.getItem("cached");
    if (!cached) {
      window.sessionStorage.setItem("cached", 1);
      this.clearCaches();
    }

    return window.caches
      .match(req)
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        return response;
      })
      .catch(async () => {
        return window.caches.open(cacheName).then(async (cache) => {
          const res = await fetch(req);
          cache.put(req, res.clone());
          return await res.json();
        });
      });
  }
  static install(Vue) {
    Vue.prototype.request = new RequestCache(process.env.VUE_APP_BASEURL);
  }
}
